// 此模块用于定义用户相关的操作: login, register, logout, getStorageData

import { defineStore } from 'pinia' // 导入pinia
import { ref } from 'vue' // 导入ref,用于定义响应式数据

import { loginAPI, registerAPI } from '@/apis/UserApi' // 导入登录和注册接口

// 定义用户相关的store
export const useUserStore = defineStore('user', () => {
  // 定义用户相关的响应式数据
  // 用户对象信息
  const userInfo = ref({})
  // token
  const token = ref('')
  // username
  const username = ref('')

  // 登录方法
  const login = async (username, password) => {
    const res = await loginAPI({ username, password }) // 异步调用登录接口
    userInfo.value = res.data.data  // 将返回的数据赋值给userInfo
    token.value = res.data.data.token
    username.value = res.data.data.username
    // 持久化存储
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    localStorage.setItem('token', token.value)
    localStorage.setItem('username', userInfo.value.username)
  }

  // 退出登录
  const logout = () => {
    userInfo.value = {}
    token.value = ''
    username.value = ''
    // 清空本地存储
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }

  // 注册方法
  const register = async (userData) => {
    const res = await registerAPI(userData) // 异步调用注册接口
    return res.data.data // 返回注册成功的数据
  }

  // 页面刷新时，用户状态保持,   从本地获取数据
  const getStorageData = () => {
    const storageUserInfo = localStorage.getItem('userInfo')
    const storageToken = localStorage.getItem('token')
    const storageUsername = localStorage.getItem('username')
    if (storageUserInfo) {
      userInfo.value = JSON.parse(storageUserInfo)
    }
    if (storageToken) {
      token.value = storageToken
    }
    if (storageUsername) {
      username.value = storageUsername
    }
  }

  return {
    userInfo,
    token,
    username,
    login,
    logout,
    register,
    getStorageData
  }
})
